package com.zackeus.mvvm.base;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @name 数据工厂基类
 * @author zz
 * @date 2022/7/19 14:28
*/ 
@SuppressWarnings({"unchecked"})
public abstract class BaseViewModelFactory<D extends BaseModel> extends ViewModelProvider.NewInstanceFactory {
    protected final Application mApplication;
    protected final D mRepository;

    protected BaseViewModelFactory(Application application) {
        this(application, null);
    }

    protected BaseViewModelFactory(Application application, D repository) {
        mApplication = application;
        mRepository = repository;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass.isAssignableFrom(BaseViewModel.class)) {
            return (T) new BaseViewModel<>(mApplication);
        }

        try {
            String className = modelClass.getCanonicalName();
            assert className != null;
            Class<?> classViewModel = Class.forName(className);

            Constructor<?> cons = classViewModel.getConstructor(Application.class, mRepository.getClass());
            ViewModel viewModel = (ViewModel) cons.newInstance(mApplication, mRepository);
            return (T) viewModel;
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Unknown ViewModel class: " + modelClass.getName());
        }
    }
}
